using System;
using System.Collections.Generic;
using System.Data;
using log4net;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace ud_Gallery.UI
{
    public class GalleryImageIndexBuilderProvider : IndexBuilderProvider
    {
        private static readonly ILog log
            = LogManager.GetLogger(typeof(GalleryImageIndexBuilderProvider));

        public override void RebuildIndex(
            PageSettings pageSettings,
            string indexPath)
        {
            if (WebConfigSettings.DisableSearchIndex) { return; }
            if (pageSettings == null) return;

            //don't index pending/unpublished pages
            if (pageSettings.IsPending) { return; }

            log.Info("GalleryImageIndexBuilderProvider indexing page - " 
                + pageSettings.PageName);

            try
            {
                Guid galleryFeatureGuid = new Guid("d572f6b4-d0ed-465d-ad60-60433893b401");
                ModuleDefinition galleryFeature = new ModuleDefinition(galleryFeatureGuid);

                List<PageModule> pageModules
                        = PageModule.GetPageModulesByPage(pageSettings.PageId);

                DataTable dataTable = GalleryImage.GetImagesByPage(pageSettings.SiteId, pageSettings.PageId);

                foreach (DataRow row in dataTable.Rows)
                {
                    IndexItem indexItem = new IndexItem
                                              {
                                                  SiteId = pageSettings.SiteId,
                                                  PageId = pageSettings.PageId,
                                                  PageName = pageSettings.PageName,
                                                  ViewRoles = pageSettings.AuthorizedRoles,
                                                  ModuleViewRoles = row["ViewRoles"].ToString()
                                              };

                    if (pageSettings.UseUrl)
                    {
                        indexItem.ViewPage = pageSettings.Url.Replace("~/", string.Empty);
                        indexItem.UseQueryStringParams = false;
                    }
                    indexItem.FeatureId = galleryFeatureGuid.ToString();
                    indexItem.FeatureName = galleryFeature.FeatureName;
                    indexItem.FeatureResourceFile = galleryFeature.ResourceFile;

                    // in compact mode use the GalleryBrowse.aspx page
                    //indexItem.ViewPage = "GalleryBrowse.aspx";

                    indexItem.ItemId = Convert.ToInt32(row["ItemID"]);
                    indexItem.ModuleId = Convert.ToInt32(row["ModuleID"]);
                    indexItem.ModuleTitle = row["ModuleTitle"].ToString();
                    indexItem.Title = row["Caption"].ToString();
                    indexItem.Content = row["Description"].ToString();

                    indexItem.QueryStringAddendum = "&ItemID"
                        + row["ModuleID"]
                        + "=" + row["ItemID"];

                    // lookup publish dates
                    foreach (PageModule pageModule in pageModules)
                    {
                        if (indexItem.ModuleId == pageModule.ModuleId)
                        {
                            indexItem.PublishBeginDate = pageModule.PublishBeginDate;
                            indexItem.PublishEndDate = pageModule.PublishEndDate;
                        }
                    }

                    IndexHelper.RebuildIndex(indexItem, indexPath);

                    if (log.IsDebugEnabled) log.Debug("Indexed " + indexItem.Title);

                }
            }
            catch (System.Data.Common.DbException ex)
            {
                log.Error(ex);
            }
            
            

        }

        public override void ContentChangedHandler(
            object sender,
            ContentChangedEventArgs e)
        {
            if (WebConfigSettings.DisableSearchIndex) { return; }
            GalleryImage galleryImage = (GalleryImage)sender;
            if (e.IsDeleted)
            {
                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                if (siteSettings == null) return;
                // get list of pages where this module is published
                List<PageModule> pageModules
                    = PageModule.GetPageModulesByModule(galleryImage.ModuleId);

                foreach (PageModule pageModule in pageModules)
                {
                    RemoveGalleryImageIndexItem(
                        siteSettings.SiteId,
                        pageModule.PageId,
                        galleryImage.ModuleId,
                        galleryImage.ItemId);
                }

            }
            else
            {
                IndexItem(galleryImage);
            }

        }

        private static void IndexItem(GalleryImage galleryImage)
        {
            if (WebConfigSettings.DisableSearchIndex) { return; }
            SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
            if ((siteSettings == null)
                    || (galleryImage == null))
            {
                return;
            }

            Guid galleryFeatureGuid = new Guid("d572f6b4-d0ed-465d-ad60-60433893b401");
            ModuleDefinition galleryFeature = new ModuleDefinition(galleryFeatureGuid);
            Module module = new Module(galleryImage.ModuleId);

            // get list of pages where this module is published
            List<PageModule> pageModules
                = PageModule.GetPageModulesByModule(galleryImage.ModuleId);

            foreach (PageModule pageModule in pageModules)
            {
                PageSettings pageSettings
                = new PageSettings(
                siteSettings.SiteId,
                pageModule.PageId);

                //don't index pending/unpublished pages
                if (pageSettings.IsPending) { continue; }

                IndexItem indexItem = new IndexItem
                                          {
                                              SiteId = siteSettings.SiteId,
                                              PageId = pageSettings.PageId,
                                              PageName = pageSettings.PageName,
                                              ViewRoles = pageSettings.AuthorizedRoles,
                                              ModuleViewRoles = module.ViewRoles,
                                              FeatureId = galleryFeatureGuid.ToString(),
                                              FeatureName = galleryFeature.FeatureName,
                                              FeatureResourceFile = galleryFeature.ResourceFile,
                                              ItemId = galleryImage.ItemId,
                                              ModuleId = galleryImage.ModuleId,
                                              QueryStringAddendum = "&ItemID"
                                                                    + galleryImage.ModuleId
                                                                    + "=" + galleryImage.ItemId,
                                              ModuleTitle = module.ModuleTitle,
                                              Title = galleryImage.Caption,
                                              Content = galleryImage.Description,
                                              PublishBeginDate = pageModule.PublishBeginDate,
                                              PublishEndDate = pageModule.PublishEndDate
                                          };

                IndexHelper.RebuildIndex(indexItem);

                if (log.IsDebugEnabled) log.Debug("Indexed " + galleryImage.Caption);
            }

        }


        private static void RemoveGalleryImageIndexItem(
            int siteId,
            int pageId,
            int moduleId, 
            int itemId)
        {
            if (WebConfigSettings.DisableSearchIndex) { return; }

            IndexItem indexItem = new IndexItem
                                      {
                                          SiteId = siteId,
                                          PageId = pageId,
                                          ModuleId = moduleId,
                                          ItemId = itemId,
                                          QueryStringAddendum = "&ItemID" + moduleId
                                                                + "=" + itemId
                                      };

            IndexHelper.RemoveIndex(indexItem);

            if (log.IsDebugEnabled) log.Debug("Removed Index ");
            

        }

    }
}
